//
//  WidgetPreviewController.swift
//  TimMusic
//
//  Created by nkl on 2024/10/23.
//

import Foundation
import KLExtension
import SwiftUI
import THUD

class WidgetPreviewController: BasicViewController {
    lazy var dismissArea: UIControl = {
        let area = UIControl()
        area.addTarget(self, action: #selector(dismissCurrentVc), for: .touchUpInside)
        return area
    }()

    lazy var bgView: UIView = .simpleView(color: .hexColor("#232323"))
    lazy var titleLabel: UILabel = .simpleLabel(text: "Preview Widget", font: .systemFont18, color: .white)
    lazy var closeBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "ic_preview_close"), for: .normal)
        btn.addTarget(self, action: #selector(dismissCurrentVc), for: .touchUpInside)
        return btn
    }()

    lazy var saveBtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("Save", for: .normal)
        btn.setTitleColor(.black, for: .normal)
        btn.backgroundColor = .white
        btn.layer.cornerRadius = 24
        btn.layer.masksToBounds = true
        btn.addTarget(self, action: #selector(saveBtnAction), for: .touchUpInside)
        return btn
    }()

    var hostVc: UIHostingController<AnyView>?

    var widgetModel: WidgetItemModel?

    override func viewDidLoad() {
        super.viewDidLoad()
        bindData()
    }

    func bindData() {
        guard let vModel = widgetModel else {
            return
        }
        let ss = AnyView(TimClassMap.map(name: vModel.fullName,isStatic: true))
        self.hostVc = UIHostingController(rootView: ss)
        guard let hostVc = hostVc else {
            return
        }
        hostVc.view.backgroundColor = .clear
        bgView.addSubview(hostVc.view)
        hostVc.view.layer.cornerRadius = 22
        hostVc.view.layer.masksToBounds = true
        hostVc.view.snp.makeConstraints { make in
            make.center.equalToSuperview()
            if vModel.type == .small {
                make.size.equalTo(TimSize.scaleSmallSize)
            } else {
                make.size.equalTo(TimSize.scaleMediumSize)
            }
        }
        addChild(hostVc)
    }

    @objc func dismissCurrentVc() {
        dismiss(animated: true)
    }

    @objc func saveBtnAction() {
        if let vModel = widgetModel {
            let newModel = WidgetItemModel(id: vModel.id, type: vModel.type, belong: vModel.belong)
            var widgetModel = MyWidgetItemModel(uidString: UUID().uuidString, date: Date(), snapshot: nil, itemModel: newModel)

            // 获取 hostVc.view 的快照
            guard let hostVc = hostVc else {
                return
            }
            if let hostViewSnapshot = captureSnapshot(of: hostVc.view) {
                widgetModel.snapshot = hostViewSnapshot.compressImageToSize()
            }

            TimDataManager.shared.appendMyWidgets(itemModel: widgetModel) { models in
                if models != nil {
                    THUD.showTips("Saved in “my widgets”", position: .top)
                    dismissCurrentVc()
                } else {
                    // 添加失败
                }
            }
        }
    }

    func captureSnapshot(of view: UIView) -> UIImage? {
        let renderer = UIGraphicsImageRenderer(size: view.bounds.size)
        return renderer.image { _ in
            view.drawHierarchy(in: view.bounds, afterScreenUpdates: true)
        }
    }

    override func addChildren() {
        super.addChildren()
        view.addSubview(dismissArea)
        view.addSubview(bgView)
        bgView.addSubview(titleLabel)
        bgView.addSubview(closeBtn)
        bgView.addSubview(saveBtn)
    }

    override func makeConstraints() {
        dismissArea.snp.makeConstraints { make in
            make.leading.top.trailing.equalToSuperview()
            make.bottom.equalTo(bgView.snp.top)
        }

        bgView.snp.makeConstraints { make in
            make.bottom.leading.trailing.equalToSuperview()
            make.height.equalTo(400)
        }

        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(20)
        }

        closeBtn.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-8)
            make.top.equalToSuperview().offset(16)
            make.width.height.equalTo(32)
        }

        saveBtn.snp.makeConstraints { make in
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            make.width.equalTo(250)
            make.height.equalTo(48)
            make.centerX.equalToSuperview()
        }
    }
}
